#ifndef _PWM_C
#define _PWM_C

#define MAX_EVENTS   10

event_T *p;
event_T *n;
event_T eventList[MAX_EVENTS];
char syncOnNextEvent;

// PWM uses TMR2
//
// T2CON
// 0b -WWW WWWW
//     ||| ||++-- Prescaler: 00=1:1, 01=1:4, 1x=1:16
//     ||| |+---- Enable: 1=On, 0=Off
//     +++-+----- Postscaler: 0000=1:1, 0001=1:2, .. 1111=1:16

void pwm_config( void )
{
//   T2CON = 0b00000111;
   T2CON = 0b00000100;
   p = eventList;
   TMR2IP = 1;    // High priority interrupt
}

void pwm_isr( void )
{
   uns16 sv_FSR0 = FSR0;

   if( syncOnNextEvent )
   {
      if( p->portC.7 )
      {
         p=n;
         syncOnNextEvent = 0;
      }
   }

   PR2 = p->match;
   PORTC = p->portC;
   p = p->next;
   FSR0 = sv_FSR0;
   TMR2IF = 0;
}

void pwm_addEvent( char index, char portC, char next, char match )
{
   eventList[index].portC = portC;
   eventList[index].match = match;
   eventList[index].next = &eventList[next];
}

void pwm_setNextEvent( char index )
{
   n = &eventList[index];
   syncOnNextEvent = 1;
}

#endif